package com.lovo.manage_back.aspect;

import com.lovo.manage_back.bean.User;
import com.lovo.manage_back.result.ResponseResult;
import com.lovo.manage_back.result.Result;
import com.lovo.manage_back.result.ResultCode;
import com.lovo.manage_back.service.LogService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Aspect
@Component
@Slf4j
public class LogAspect {
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private LogService logService;
    @Around("execution(* com.lovo..*.controller..*(..))")
    public Object insertLog(ProceedingJoinPoint joinPoint)throws Throwable{
        Object obj = null;
        Method targetMethod = null;
        try {
            Signature signature = joinPoint.getSignature();
            MethodSignature methodSignature = (MethodSignature)signature;
            targetMethod = methodSignature.getMethod();

            obj = joinPoint.proceed(joinPoint.getArgs());
            //判断方法上是否加了注解
            if (isAnnotationPresent(targetMethod)) {
                Log annotation = targetMethod.getAnnotation(Log.class);
                String value = annotation.value();
                com.lovo.manage_back.bean.Log log = new com.lovo.manage_back.bean.Log();
                User user = (User) request.getAttribute("user");
                LocalDateTime now = LocalDateTime.now();
                log.setDate(now);
                log.setCreateTime(now);
                log.setUpdateTime(now);
                log.setContent("用户" + user.getUsername()
                        + "在"
                        + DateTimeFormatter.ofPattern("HH点mm分").format(now)
                        + value);
                logService.save(log);
            }
        }catch (Throwable e){
            throw e;
        }
        return obj;
    }

    private boolean isAnnotationPresent(Method method){
        return method.isAnnotationPresent(Log.class);

    }
}
